package org.example.springtest.util;

import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.example.springtest.config.JwtProperties;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {
    public static long expiration = System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 30  ;

    public static HashMap<String, Integer> getExpiration() {
        HashMap<String, Integer> scores = new HashMap<>();
        long millisecond = expiration - System.currentTimeMillis();
        int hour = (int) (millisecond / (1000L * 60 * 60));
        scores.put("millisecond", (int) (millisecond) );
        scores.put("hour", hour);
        return scores;
    }

    private static JwtProperties jwtProperties;
    public JwtUtil(JwtProperties jwtProperties) {
        JwtUtil.jwtProperties = jwtProperties;
    }

    // 生成 token
    public static String generateToken(String username, String id) {
        SecretKey key = Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8));
        return Jwts.builder()
                .setSubject(id) // 用 id 作为 subject
                .claim("username", username) // 自定义字段
                .setIssuedAt(new Date())
                .setExpiration(new Date(expiration)) // 30天
                .signWith(key)
                .compact();
    }
    // 校验并解析 token
    public static String validateTokenAndGetUsername(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)).build()
                    .parseClaimsJws(token)
                    .getBody()
                    .getSubject();
        } catch (JwtException e) {
            return null; // 无效 token
        }
    }
}
